package com.jf.net.gson

import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter

/**
 * IntegerDefaultAdapter
 * @author JackyFlame
 * @time 2023/10/20 14:12
 * @description
 */
class IntegerDefaultAdapter : TypeAdapter<Int>(){

    companion object{
        const val DEFAULT_VALUE = 0
    }

    override fun write(out: JsonWriter, value: Int?) {
        out.value(value)
    }

    override fun read(jr: JsonReader): Int {
        return when (jr.peek()) {
            JsonToken.NUMBER ->
                try {
                    jr.nextInt()
                } catch (e: NumberFormatException) {
                    DEFAULT_VALUE
                }
            JsonToken.STRING ->
                try {
                    jr.nextString().toInt()
                } catch (e: NumberFormatException) {
                    DEFAULT_VALUE
                }
            JsonToken.NULL -> {
                jr.nextNull()
                DEFAULT_VALUE
            }
            else -> DEFAULT_VALUE
        }
    }
}